package com.wejoy.video.middle.station.admin.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.wejoy.video.middle.station.admin.controller.BaseController;
import com.wejoy.video.middle.station.admin.util.CurrentUserUtils;
import com.wejoy.video.middle.station.data.annotation.RoleCheck;
import com.wejoy.video.middle.station.data.domain.PageResult;
import com.wejoy.video.middle.station.data.domain.system.*;
import com.wejoy.video.middle.station.data.enums.dict.EnumOrderRoleType;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.system.*;
import com.wejoy.video.middle.station.data.util.DateUtils;
import com.wejoy.video.middle.station.data.util.RSAUtil;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.util.user.SysUserLoginUtil;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.evsapi.DeparmentInfoListVO;
import com.wejoy.video.middle.station.data.vo.system.SystemInfoAndUserInfoVo;
import com.wejoy.video.middle.station.data.vo.system.UserPasswordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统--用户表
 *
 * @author admin
 * @date 2021年10月19日 15:07:06
 */
@RestController
@RequestMapping("/system/sysUser")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysRoleResourceService roleResourceService;
    @Autowired
    private ISysBaseParamService sysBaseParamService;
    @Autowired
    private IEvsHttpService evsHttpService;
    @Autowired
    private ISysRoleOrderService sysRoleOrderService;
    /**
     * 图片路径
     */
    @Value("${qiniu.prefix}")
    private String uri;

    /**
     * 保存或更新
     *
     * @param sysUserReq sysUserReq
     * @return RespJSON
     */
    @PostMapping("/save")
    @RoleCheck(name = "sys_user_add")
    public RespJSON save(@RequestBody SysUser sysUserReq, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        try {
            sysUserReq.setPassword(RSAUtil.decrypt(sysUserReq.getPassword(),RSAUtil.private_key));
        } catch (Exception e) {
            throw new BusinessException("非法参数");
        }
        sysUserService.save(sysUserReq, loginSysUser.getUserName());
        return RespJSON.success();
    }

    /**
     * 分页查询
     *
     * @param sysUserReq sysUserReq
     * @return RespJSON
     */
    @PostMapping("/getPageList")
    @RoleCheck(name = "sys_user_list")
    public RespJSON getPageList(@RequestBody SysUser sysUserReq,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        com.alibaba.fastjson2.JSONObject users = evsHttpService.getUsers(sysUserReq.getDepartmentId(), sysUserReq.getPageNo(), sysUserReq.getPageSize(), sysUserReq.getName(), sysUserReq.getPhone(), loginSysUser.getToken());
        JSONArray data = users.getJSONArray("data");
        List<SysUser> list = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            com.alibaba.fastjson2.JSONObject user = data.getJSONObject(i);
            SysUser sysUser = new SysUser();
            sysUser.setName(user.getString("userName"));
            sysUser.setId(user.getLong("userId"));
            sysUser.setTel(user.getString("tel"));
            sysUser.setDepartmentName(user.getString("departmentName"));
            list.add(sysUser);
        }
//        List<SysUser> list = JSONArray.parseArray(users.getString("data"), SysUser.class);
        Integer count = users.getInteger("totalCount");
        //        int count = sysUserService.getCount(sysUserReq);
//        List<SysUser> list = new ArrayList<>();
//        if (count > 0) {
//            list = sysUserService.getPageList(sysUserReq);
//        }
        PageResult result = new PageResult(sysUserReq.getPageNo(), sysUserReq.getPageSize(), count, list);
        return RespJSON.success(result);
    }

//    /**
//     * 分页查询
//     *
//     * @param sysUserReq sysUserReq
//     * @return RespJSON
//     */
//    @PostMapping("/getDataPermissionPageList")
//    public RespJSON getDataPermissionPageList(@RequestBody SysUser sysUserReq,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
//        if(CollectionUtils.isEmpty(loginSysUser.getManageDeptIdList())){
//            return RespJSON.success();
//        }
//        sysUserReq.setDataPermissionDeptIds(loginSysUser.getManageDeptIdList());
//        int count = sysUserService.getDataPermissionCount(sysUserReq);
//        List<SysUser> list = new ArrayList<>();
//        if (count > 0) {
//            list = sysUserService.getDataPermissionPageList(sysUserReq);
//        }
//        PageResult result = new PageResult(sysUserReq.getPageNo(), sysUserReq.getPageSize(), count, list);
//        return RespJSON.success(result);
//    }


    /**
     * 主键查询
     *
     * @param id id
     * @return RespJSON
     */
    @RequestMapping("/getOneById")
    public RespJSON getOneById(Long id) {
        return RespJSON.success(sysUserService.getOneById(id));
    }

//    /**
//     * 主键查询
//     *
//     * @param id id
//     * @return RespJSON
//     */
//    @PostMapping("/delete")
//    @RoleCheck(name = "sys_user_delete")
//    public RespJSON delete(Long id, @SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
//        sysUserService.delete(id, loginSysUser.getUserName());
//        return RespJSON.success();
//    }


    /**
     * 登陆
     * <p>
     * param username 用户名
     * param password 密码
     *
     * @return
     */
    @PostMapping("/login")
    public RespJSON login(@RequestBody SysUser sysUser, HttpServletRequest request) {
//        try {
//            sysUser.setPassword(RSAUtil.decrypt(sysUser.getPassword(),RSAUtil.private_key));
//        } catch (Exception e) {
//            throw new BusinessException("非法参数");
//        }
        SysUser sysUserDB = sysUserService.login(sysUser);
        SysUserLoginUtil.saveInCache(sysUserDB, request);
        return RespJSON.success(sysUserDB.getToken());
    }


    /**
     * 注销
     *
     * @return
     */
    @PostMapping("/logout")
    public RespJSON logout(@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        SysUserLoginUtil.clearUserCache(loginSysUser.getToken());
        return RespJSON.success();
    }

    /**
     * 获取当前用户信息
     *
     * @param loginSysUser
     * @return
     */
    @GetMapping("/getCurrentUser")
    public RespJSON getCurrentUserAndRole(@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        List<SysRole> currentUserRole = sysRoleService.getCurrentUserRole(loginSysUser);
        loginSysUser.setSysRoleList(currentUserRole);
        List<String> sysResourceIdentityList = new ArrayList<>();
        List<SysResource> sysResourceList = new ArrayList<>();
        roleResourceService.buildUserResourceListAndIdentityList(currentUserRole, sysResourceList, sysResourceIdentityList);
        if (CollectionUtils.isEmpty(currentUserRole)) {
            currentUserRole = new ArrayList<>();
            SysRole sysRole = new SysRole();
            sysRole.setName("首页");
            currentUserRole.add(sysRole);
            loginSysUser.setSysRoleList(currentUserRole);
        }
        //查询用户默认工单权限部门
        List<Long> deptIds = getDeptIds(loginSysUser);
        if(CollectionUtils.isEmpty(deptIds)){
            //项目管理员
            if(loginSysUser.getType().equals("project_admin")){
                deptIds.add(EnumOrderRoleType.ALL_ROLE.getCode().longValue());
                loginSysUser.setDataPermissionDeptIds(deptIds);
            }
            //普通用户默认查询本部门工单，不包含子部门
            if(loginSysUser.getType().equals("ordinary_user")){
                loginSysUser.setDataPermissionDeptIds(loginSysUser.getDepartmentInfoList().stream()
                        .map(DeparmentInfoListVO::getDepartmentId) // 提取每个SysRoleOrder对象的id属性
                        .collect(Collectors.toList()));
            }
        }else {
            loginSysUser.setDataPermissionDeptIds(deptIds);
        }
        loginSysUser.setSysResourceList(sysResourceList);
        loginSysUser.setSysResourceIdentityList(sysResourceIdentityList);
        SysUserLoginUtil.refreshCache(loginSysUser.getToken(),loginSysUser,null);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(loginSysUser));
        jsonObject.put("id","");
        jsonObject.put("phone","");
        jsonObject.put("password","");
        jsonObject.put("token","");
        return RespJSON.success(jsonObject);
    }

    private List<Long> getDeptIds(SysUser loginSysUser){
        List<Long> ids = new ArrayList<>();
        SysRoleOrder sysRoleOrder = new SysRoleOrder();
        sysRoleOrder.setUserId(loginSysUser.getId());
        List<SysRoleOrder> list = sysRoleOrderService.getList(sysRoleOrder);
        if(CollectionUtils.isEmpty(list)){
            return ids;
        }
        if(list.size()==1){
            SysRoleOrder roleOrder = list.get(0);
            //本部门
            if(roleOrder.getDeptId() == 0){
                if(CollectionUtils.isEmpty(loginSysUser.getDepartmentInfoList())){
                    return ids;
                }
                ids = loginSysUser.getDepartmentInfoList().stream()
                        .map(DeparmentInfoListVO::getDepartmentId) // 提取每个SysRoleOrder对象的id属性
                        .collect(Collectors.toList());// 收集到新的ArrayList中
                return ids;
            }
            if(roleOrder.getDeptId() == 1){
                if(CollectionUtils.isEmpty(loginSysUser.getDepartmentInfoList())){
                    return ids;
                }
                List<Long> finanList = new ArrayList<>();
                loginSysUser.getDepartmentInfoList().forEach(item->{
                    getIds(item.getDepartmentId(),loginSysUser.getToken(), finanList);
                    if (!finanList.contains(item.getDepartmentId())) {
                        finanList.add(item.getDepartmentId());
                    }
                });
                //返回去重后的list
                return finanList.stream().distinct().collect(Collectors.toList());
            }
            if(roleOrder.getDeptId() == 3){
                ids.add(EnumOrderRoleType.ALL_ROLE.getCode().longValue());
                return ids;
            }
            //子部门
            return ids;
        }
        //自定义部门
        ids=list.stream()
                .map(SysRoleOrder::getDeptId) // 提取每个SysRoleOrder对象的id属性
                .collect(Collectors.toList()); // 收集到新的ArrayList中
        return ids;
    }

    /**
     * 获取子部門的所有id
     */
    private void getIds(Long deptId,String token,List<Long> ids){
        SysDept evsApiDept = new SysDept();
        evsApiDept.setParentId(deptId.intValue());
        evsApiDept.setIncludeLower(true);
        List<SysDept> departments = evsHttpService.getDepartments(evsApiDept, token);
        List<Long> collect = departments.stream()
                .map(SysDept::getId) // 提取每个SysRoleOrder对象的id属性
                .collect(Collectors.toList());// 收集到新的ArrayList中
        ids.addAll(collect);
    }

    /**
     * 获取当前用户信息和系统信息
     * @param loginSysUser
     * @return
     */
    @GetMapping("/systemInfoAndUserInfo")
    @RoleCheck(name = "accountSettings")
    public RespJSON systemInfoAndUserInfo(@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser){
        SystemInfoAndUserInfoVo systemInfoAndUserInfoVo = new SystemInfoAndUserInfoVo();
        SysBaseParam systemContext = sysBaseParamService.getOneByUniCode("SYSTEM_CONTEXT");
        SysBaseParam systemUpdatetime = sysBaseParamService.getOneByUniCode("SYSTEM_UPDATETIME");
        SysBaseParam systemVersion = sysBaseParamService.getOneByUniCode("SYSTEM_VERSION");
        SysBaseParam systemVideoUrl = sysBaseParamService.getOneByUniCode("SYSTEM_VIDEO_URL");
        SysBaseParam systemreminder = sysBaseParamService.getOneByUniCode("SYSTEM_REMINDER");
        SysBaseParam systemInitiate = sysBaseParamService.getOneByUniCode("SYSTEM_INITIATE");
        SysBaseParam systemUserManagement = sysBaseParamService.getOneByUniCode("SYSTEM_USER_MANAGEMENT");
        systemInfoAndUserInfoVo.setContex(systemContext==null?"":systemContext.getValue());
        systemInfoAndUserInfoVo.setUpdateTime(systemUpdatetime==null?"":systemUpdatetime.getValue());
        systemInfoAndUserInfoVo.setVersion(systemVersion==null?"":systemVersion.getValue());
//        systemInfoAndUserInfoVo.setCreateTime(DateUtils.formatDateTime(loginSysUser.getCreateTime()));
//        StringBuilder deptName = new StringBuilder("");
//        loginSysUser.getDeptUserList().forEach(item -> {
//            deptName.append(item.getDeptName()+" ");
//        });
        List<String> names = new ArrayList<>();
        if(!CollectionUtils.isEmpty(loginSysUser.getDepartmentInfoList())){
            loginSysUser.getDepartmentInfoList().forEach(item->{
                names.add(item.getDepartmentPath());
            });
        }
        systemInfoAndUserInfoVo.setDeptName(names.toString().substring(1, names.toString().length() - 1));
        systemInfoAndUserInfoVo.setUserManagement(systemUserManagement==null?"":systemUserManagement.getValue());
        systemInfoAndUserInfoVo.setReminder(systemreminder==null?"":systemreminder.getValue());
        systemInfoAndUserInfoVo.setInitiate(systemInitiate==null?"":systemInitiate.getValue());
        systemInfoAndUserInfoVo.setVideoUrl(systemVideoUrl==null?"":systemVideoUrl.getValue());
        systemInfoAndUserInfoVo.setUsername(loginSysUser.getUserName());
//        com.alibaba.fastjson2.JSONObject user = evsHttpService.getUserById(loginSysUser.getId(), loginSysUser.getToken());
//        systemInfoAndUserInfoVo.setDeptName(user.getString(""));
        systemInfoAndUserInfoVo.setPassword("************");
        systemInfoAndUserInfoVo.setName(loginSysUser.getName());
        systemInfoAndUserInfoVo.setPhone(loginSysUser.getTel());
        systemInfoAndUserInfoVo.setJobName(loginSysUser.getJobName());
        return RespJSON.success(systemInfoAndUserInfoVo);
    }

    /**
     * 修改密码
     *
     * @param userPasswordVO
     * @param loginSysUser
     * @return
     */
    @PostMapping("/updatePassword")
    public RespJSON login(@RequestBody UserPasswordVO userPasswordVO,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        try {
            userPasswordVO.setOldPassword(RSAUtil.decrypt(userPasswordVO.getOldPassword(),RSAUtil.private_key));
            userPasswordVO.setNewPassword(RSAUtil.decrypt(userPasswordVO.getNewPassword(),RSAUtil.private_key));
        } catch (Exception e) {
            throw new BusinessException("非法参数");
        }
        WJAssert.isMaxLength(userPasswordVO.getOldPassword(), 32, "旧密码错误");
        WJAssert.isMaxLength(userPasswordVO.getNewPassword(), 32, "新密码错误");
        sysUserService.updatePassword(userPasswordVO.getOldPassword(), userPasswordVO.getNewPassword(), loginSysUser.getId());
        return RespJSON.success();
    }

    /**
     * 修改密码
     *
     * @param phone
     * @param loginSysUser
     * @return
     */
    @PostMapping("/updatePhone")
    public RespJSON login(String phone,@SessionAttribute(CurrentUserUtils.SYSTEM_USER) SysUser loginSysUser) {
        WJAssert.isMaxLength(phone, 11, "手机号错误");
        sysUserService.updatePhone(phone, loginSysUser.getId());
        return RespJSON.success();
    }
}
